import { ref } from "vue";
import cloneDeep from "lodash/cloneDeep";
import { initFormData } from "@/utils/init";

// ui-modal-form 组件的 hook
export function useUiModalFormHook(storeAdapterConfig, modalForm, modalFormConfigProxy, uiModalFormRef, callback) {
  // 当前模式：create | edit | check
  const mode = ref("");

  // 校验组件实例是否存在
  const validateUiModalFormDom = () => {
    if (!uiModalFormRef || !uiModalFormRef.value) {
      console.warn("uiModalFormRef 未传入或未挂载");
      return false;
    }
    return true;
  };

  // 修改表单禁用状态
  const updateModalFormDisabled = (disabled) => {
    modalFormConfigProxy.value.formAttributes.disabled = disabled;
  };

  // 打开弹框
  const openModal = (title) => {
    if (!validateUiModalFormDom()) return;
    uiModalFormRef.value.open();
    uiModalFormRef.value.updateDialogTitle(title);
  };

  // 关闭弹框
  const closeModal = () => {
    if (!validateUiModalFormDom()) return;
    uiModalFormRef.value.close();
  };

  // 初始化表单数据并打开弹框
  const initModalForm = (modeType, data) => {
    mode.value = modeType;

    switch (modeType) {
      case "create":
        modalForm.value = initFormData(modalFormConfigProxy.value.formItems);
        updateModalFormDisabled(false);
        openModal("新建");
        break;
      case "edit":
        modalForm.value = cloneDeep(data);
        updateModalFormDisabled(false);
        openModal("编辑");
        break;
      case "check":
        modalForm.value = { ...data };
        updateModalFormDisabled(true);
        openModal("预览");
        break;
    }

    callback && callback(modeType + "Hook");
  };

  // 新建
  const createHook = () => initModalForm("create");

  // 编辑
  const editHook = (row) => initModalForm("edit", row);

  // 查看
  const checkHook = (row) => initModalForm("check", row);

  // 确认（区分 新建 / 编辑）
  const confirmHook = () => {
    if (!validateUiModalFormDom()) return;

    uiModalFormRef.value.validateModalForm(async (valid) => {
      if (!valid) return;

      try {
        if (mode.value === "create") {
          await storeAdapterConfig.createRow(modalForm.value);
        } else if (mode.value === "edit") {
          await storeAdapterConfig.updateRow(modalForm.value);
        }
      } catch (error) {
        console.error("操作失败:", error);
      } finally {
        closeModal();
        callback && callback("confirmHook");
      }
    });
  };

  // 取消
  const cancelHook = () => closeModal();

  return { createHook, editHook, checkHook, confirmHook, cancelHook };
}
